package com.liu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liu.pojo.Employee;
import com.liu.pojo.Msg;
import com.liu.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: lsp
 * @Date: 21:27 2020/5/19
 * @Description: 处理员工CRUD请求
 **/

@Controller

public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
    /**
     * @Description 批量删除
     * @Param [ids]
     * @return com.liu.pojo.Msg
     **/
    @ResponseBody
    @RequestMapping(value = "/emp/{ids}",method = RequestMethod.DELETE)
    public Msg deleteEmp(@PathVariable String ids){
        List<Integer> del_ids = new ArrayList<>();
//        System.out.println(ids);
        if (ids.contains("-")){
            String[] str_ids = ids.split("-");
            for (String id : str_ids) {
                del_ids.add(Integer.parseInt(id));
            }
            employeeService.deleteBatch(del_ids);

        }else {
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }

        return Msg.success();
    }
    /**
     * @Description 根据id修改员工信息
     * @Param [employee]
     * @return com.liu.pojo.Msg
     **/

    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg saveEmp(Employee employee){
        System.out.println(employee);
        employeeService.updateEmp(employee);
        return Msg.success();
    }
/**
 * @Description 根据id查询员工
 * @Param [id]
 * @return com.liu.pojo.Msg
 **/
    @ResponseBody
    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    public Msg getEmp(@PathVariable Integer id){
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp",employee);
    }

    /**
     * @Description 检查用户名是否可用
     * @Param [empName]
     * @return com.liu.pojo.Msg
     **/
    @ResponseBody
    @RequestMapping("/checkUser")
    public Msg checkUser(@RequestParam("empName") String empName){
        //先判断用户名是否是合法的表达式
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        if(!empName.matches(regx)){
            return Msg.fail().add("va_msg","后端：用户名可以是2-5位中文或者6-16位英文和数字的组合");
        }
        //数据库用户名重复校验
        boolean b = employeeService.checkUser(empName);
        if(b){
            return Msg.success();
        }else {
            return Msg.fail().add("va_msg","用户名不可用");
        }
    }

    /**
     * @Description 员工保存
     * @Param []
     * @return com.liu.pojo.Msg
     **/
    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
//        校验失败应该返回失败，在模态框中显示失败信息
        if (result.hasErrors()){
            Map<String,Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("错误的字段名："+fieldError.getField());
                System.out.println("错误信息："+fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields",map);
        }else {
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }

/**
 * @Description 导入jackson将对象序列化为json字符串
 * @Param [pn, model]
 * @return com.github.pagehelper.PageInfo
 **/
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpWithJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){

        PageHelper.startPage(pn,5);
        List<Employee> emps = employeeService.getAll();
//       封装了详细的分页信息，包括查询的数据，传入显示的页数
        PageInfo page = new PageInfo(emps,5);
        return Msg.success().add("pageInfo",page);
    }
/**
 * @Description 查询员工数据（分页查询）
 * @Param []
 * @return java.lang.String
 **/
//    @RequestMapping("/emps")
    public String getEmp(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
        PageHelper.startPage(pn,5);
       List<Employee> emps = employeeService.getAll();
//       封装了详细的分页信息，包括查询的数据，传入显示的页数
       PageInfo page = new PageInfo(emps,5);
       model.addAttribute("pageInfo",page);
        return "list";
    }
}
